#include "checkoutmanagement.h"
#include "ui_checkoutmanagement.h"

checkoutManagement::checkoutManagement(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::checkoutManagement)
{
    ui->setupUi(this);

    db = QSqlDatabase::database("conn");//链接数据库
    initList();
}

checkoutManagement::~checkoutManagement()
{
    delete ui;
}

void checkoutManagement::initList()
{
    ui->ordersList->clear();//清空表格

    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    QString sqlSelect = QString ("select * from orders where state = '未交易';");
    if(!query.exec(sqlSelect)){//遍历表单
        qDebug() << "select data error" << db.lastError();
    }else {
        while(query.next()){//读取数据库，填写表单
            int id = query.value("id").toInt();
            QString date = query.value("date").toString();
            QString address = query.value("address").toString();
            QString customer = query.value("customer").toString();
            QString phone = query.value("phone").toString();
            QString state = query.value("state").toString();
            QString content = query.value("content").toString();
            ordersForm* ordersItem = new ordersForm;
            ordersItem->setOrders(id,date,address,customer,phone,state);
            QListWidgetItem* item = new QListWidgetItem;

            item->setSizeHint(QSize(1420,70));
            ui->ordersList->addItem(item);
            ui->ordersList->setItemWidget(item,ordersItem);
        }
    }
}

void checkoutManagement::drawPic(QPrinter *printerPixmap)
{
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);//减少内存浪费
    QString content,address;
    QStringList list;
    double originalTotal = 0;
    double currentTotal = 0;

    QString sqlSelect = QString ("select * from orders where id = %1;").arg(globalid);
    if(!query.exec(sqlSelect)){
        qDebug() << "select data error" << db.lastError();
        return;
    }else {
        if(query.next()){
            address = query.value("address").toString();
            if(address.startsWith("T")){
                address = "堂食";
            }else{
                address = "外带";
            }
            content = query.value("content").toString();
            list = content.split(" ",QString::SkipEmptyParts);//将订单中的菜品分别列出
        }
    }

    QString sqlUpdate = QString ("update orders set state = '已完成' where id = %1;").arg(globalid);
    if(!query.exec(sqlUpdate)){
        qDebug() << "update data error" << db.lastError();
    }

    int lineY = 100 + 15 * (list.size() + 2);

    QPixmap pix = QPixmap(300,500);//画打印模板
    QPainter *painter = new QPainter(this);
    painter->begin(&pix);
    painter->setRenderHint(QPainter::Antialiasing, true);
    painter->setPen(QPen(QColor(255, 255, 255), 2));//设置画刷颜色
    painter->setBrush(QColor(255, 255, 255));
    QRect rect(0,0,300,500);//整张图设置画刷白底
    painter->fillRect(rect,QColor(255, 255, 255));
    painter->drawRect(rect);

    QPen pen;
    QVector<qreal>dashes;
    qreal space = 4;//虚线间空白
    dashes << 10 << space;
    pen.setDashPattern(dashes);
    painter->setPen(pen);//虚线
    QVector<QLine> lines;
    lines.append(QLine(QPoint(20,50),QPoint(290,50)));//分隔线
    lines.append(QLine(QPoint(20,100),QPoint(290,100)));
    lines.append(QLine(QPoint(20,lineY),QPoint(290,lineY)));
    lines.append(QLine(QPoint(20,lineY + 80),QPoint(290,lineY + 80)));
    painter->drawLines(lines);

    QFont font;
    font.setPointSize(9);
    font.setFamily("黑体");
    painter->setFont(font);
    painter->drawText(115,0,120,30,Qt::AlignVCenter,"小王饭店");

    font.setPointSize(7);
    painter->setFont(font);
    painter->drawText(90,20,120,30,Qt::AlignVCenter,"电话：12345678901");
    font.setPointSize(5);
    font.setItalic(true);//斜体
    painter->setFont(font);
    painter->drawText(120,45,120,30,Qt::AlignVCenter,"订单编号：" + QString::number(globalid));
    QString time = QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm");
    painter->drawText(110,60,120,30,Qt::AlignVCenter,time);
    painter->drawText(135,75,120,30,Qt::AlignVCenter,address);

    //painter->drawText(110,60,120,30,Qt::AlignVCenter,);

    font.setItalic(false);//取消斜体
    font.setPointSize(5);
    painter->setFont(font);
    painter->drawText(40,95,120,30,Qt::AlignVCenter,"菜品名");
    painter->drawText(175,95,120,30,Qt::AlignVCenter,"原价/元");
    painter->drawText(217,95,120,30,Qt::AlignVCenter,"折扣");
    painter->drawText(245,95,120,30,Qt::AlignVCenter,"现价/元");
    for(int i = 0;i < list.size();i++){
        //qDebug() << list.at(i);
        painter->drawText(40,100 + 15 * (i + 1),120,30,Qt::AlignVCenter,list.at(i));
        QString sqlSelect = QString ("select * from menu where name = '%1';").arg(list.at(i));
        if(!query.exec(sqlSelect)){//遍历menu表单
            qDebug() << "insert data error" << db.lastError();
        }else {
            while(query.next()){
                int originalPrize = query.value("prize").toInt();
                double discount = query.value("discount").toDouble();
                double currentPrize = originalPrize * discount;
                painter->drawText(190,100 + 15 * (i + 1),120,30,
                                  Qt::AlignVCenter,QString::number(originalPrize));
                originalTotal += originalPrize;
                if(discount < 1){
                    painter->drawText(220,100 + 15 * (i + 1),120,30,
                                      Qt::AlignVCenter,QString::number(discount));
                }
                painter->drawText(250,100 + 15 * (i + 1),120,30,
                                  Qt::AlignVCenter,QString::number(currentPrize));
                currentTotal += currentPrize;
            }
        }
    }

    double receive = QInputDialog::getDouble(this,"结账",QString("合计%1元，请输入实收金额：").arg(currentTotal));

    painter->drawText(200,lineY,120,30,Qt::AlignVCenter,"合计 " + QString::number(currentTotal) + " 元");
    painter->drawText(200,lineY + 15,120,30,Qt::AlignVCenter,
                      "优惠 " + QString::number(originalTotal - currentTotal) + " 元");
    painter->drawText(200,lineY + 30,120,30,Qt::AlignVCenter,"实收 " + QString::number(receive) + " 元");
    painter->drawText(200,lineY + 45,120,30,Qt::AlignVCenter,
                      "找零 " + QString::number(receive - currentTotal) + " 元");
    font.setPointSize(7);
    painter->setFont(font);
    painter->drawText(90,lineY + 100,120,30,Qt::AlignVCenter,"期待您的下次光临！");

    printerPixmap->setOrientation(QPrinter::Portrait);//纵向：Portrait 横向：Landscape
    QPainter painterPixmap(this);//获取界面的图片
    painterPixmap.begin(printerPixmap);
    QRect prect = painterPixmap.viewport();
    int x = prect.width() / pix.width();
    int y = prect.height() / pix.height();//设置图像长宽是原图的多少倍
    painterPixmap.scale(x, y);
    painterPixmap.drawPixmap(0, 0, pix);
    painterPixmap.end();

    initList();
}

void checkoutManagement::on_ordersList_itemClicked(QListWidgetItem *item)
{
    ordersForm* orders =dynamic_cast<ordersForm*>(ui->ordersList->itemWidget(item));//获取列表元素对应的的itemForm
    globalid = orders->getName();//获取对应订单id

    QMessageBox::StandardButton confirm = QMessageBox::Yes;
    confirm = QMessageBox::question(this,"友情提示",QString("为编号为%1的订单结账？").arg(globalid));
    if(confirm == QMessageBox::No){
        return;
    }

    emit checkoutSend("#4#结账");

    QPrinter printer(QPrinter::HighResolution);
    printer.setPageSize(QPrinter::Custom);
    printer.setPaperSize(QSizeF(300,500),QPrinter::Point);
    QPrintPreviewDialog preview(&printer,this);

    connect(&preview, SIGNAL(paintRequested(QPrinter*)),this,SLOT(drawPic(QPrinter*)));
    preview.exec();
}
